<!DOCTYPE HTML>
<html>
<head>
    <title>短租预订</title>
    <% include common/meta.ejs %>
    <% include common/public.ejs %>
    <link rel="stylesheet" type="text/css" href="<%= global.config.publicPath %>/jQueryTime/css/dateRange.css"/>
</head>
<body ontouchstart="" style="padding-bottom: 45px;height:auto;">
<div class="weui_panel weui_panel_access">
    <div class="weui_panel_bd">
        <div class="weui_media_box weui_media_text" style="padding: 1rem;">
            <p style="font-weight:700;font-size: 0.7rem;color: #141414;margin-bottom: 0.2rem"><%= data.shortDesc %></p>
            <p class="weui_media_desc"><%= data.name %></p>
            <p class="weui_media_desc">
                ￥<%= data.shortPrices.SRT00 %>/天
                ￥<%= data.shortPrices.SRT03 %>/3h
                ￥<%= data.shortPrices.SRT05 %>/5h
                ￥<%= data.shortPrices.SRT08 %>/8h
            </p>
        </div>
    </div>
</div>

<div class="weui_cells_title">预订人信息</div>
<div class="weui_cells" style="font-size: 0.7rem;">
    <div class="weui_cell">
        <div class="weui_cell_bd weui_cell_primary">
            <p>预订人：</p>
        </div>
        <div class="weui_cell_ft">
            <%=userData.name%>
        </div>
    </div>
    <div class="weui_cell">
        <div class="weui_cell_bd weui_cell_primary">
            <p>手机号：</p>
        </div>
        <div class="weui_cell_ft">
            <%=userData.phone%>
        </div>
    </div>
</div>

<form id="reservedForm">
    <input type="hidden" name="rentPrice" id="rentPrice" />
    <input type="hidden" name="couponAmount" id="couponAmount" />
    <input type="hidden" name="days" id="days" />
    <input type="hidden" name="houseName" value="<%= data.name %>" />
    <input type="hidden" name="house.id" value="<%= queryData.houseId %>" />
    <input type="hidden" name="user.id" value="<%= userData.id %>" />
    <input type="hidden" name="coupon.id" id="coupon_id" value="" />
    <div class="weui_cells_title">请填写您的预订信息</div>
    <div class="weui_cells weui_cells_form">
        <div class="weui_cell weui_cell_select">
            <div class="weui_cell_bd weui_cell_primary">
                <select class="weui_select" name="orderType" id="orderType">
                    <option selected="" value="">选择入住方式</option>
                    <option value="SRM02">日租</option>
                    <option value="SRM01">钟点房</option>
                </select>
            </div>
        </div>
        <div class="weui_cell weui_cell_select timeHouse ">
            <div class="weui_cell_bd weui_cell_primary">
                <select class="weui_select" name="shortRentType" id="timeSet">
                    <option selected="" value="SRT00">选择钟点类型</option>
                    <option value="SRT03">3小时</option>
                    <option value="SRT05">5小时</option>
                    <option value="SRT08">8小时</option>
                </select>
            </div>
        </div>
        <div class="weui_cell timeHouse">
            <div class="weui_cell_hd"><label for="" class="weui_label">入住时间</label></div>
            <div class="weui_cell_bd weui_cell_primary">
                <input class="weui_input" type="date" id="dateTimePicker" placeholder="请选择入住时间" data-toggle='date' />
                <input type="hidden" name="arrivedDate" />
                <input type="hidden" name="leavedDate"  />
            </div>
        </div>
        <div class="weui_cell dayHouse">
            <div class="weui_cell_hd"><label for="" class="weui_label">住宿时间</label></div>
            <div class="weui_cell_bd weui_cell_primary">
                <input class="weui_input" type="string" id="datePicker" placeholder="请选择入住时间" data-toggle='date' readonly />
                <input type="hidden" name="arrivedDate" id="arrivedDate" />
                <input type="hidden" name="leavedDate" id="leavedDate"  />
            </div>
        </div>
        <div class="weui_cell weui_cell_switch">
            <div class="weui_cell_hd weui_cell_primary">是否加床</div>
            <div class="weui_cell_ft">
                <input class="weui_switch" type="checkbox" id="bedFlag" name="house.addBedAble"/>
            </div>
        </div>
        <div class="weui_cell bedNumber">
            <div class="weui_cell_hd"><label class="weui_label">加床数量</label></div>
            <div class="weui_cell_bd weui_cell_primary">
                <input class="weui_input" type="number" placeholder="请输入加床数量" />
            </div>
        </div>
        <div class="weui_cell useCoupon">
            <div class="weui-cell_hd"><label for="name" class="weui_label">是否使用优惠券</label></div>
            <div class="weui-cell_bd">
                <input class="weui_input" id="useCoupon" type="text" value="" style="text-align: right">
            </div>
        </div>
    </div>

    <div class="weui_cells_title">备注</div>
    <div class="weui_cells weui_cells_form">
        <div class="weui_cell">
            <div class="weui_cell_bd weui_cell_primary">
                <textarea class="weui_textarea" placeholder="" rows="3" name="remark"></textarea>
            </div>
        </div>
    </div>
</form>
<div class="bottomBar">
    <table class="bottomTable">
        <tbody>
            <tr>
                <td>
                    <input type="hidden" value="<%= data.shortPrices.SRT00 %>" id="dayPrice" />
                    <span class="bottomInfo">总额 <span class="color-warning orderAmount">￥0</span></span>
                    <span class="bottomRemark">查看明细</span>
                </td>
                <td style="width:100px;">
                    <a href="javascript:void(0)" class="weui_btn weui_btn_primary" id="submitBtn">提交订单</a>
                </td>
            </tr>
        </tbody>
    </table>
</div>

<% include common/footer.ejs %>
<script type="text/javascript" src="<%= global.config.publicPath %>/jQueryTime/js/dateRange.js"></script>
<script>
    "use strict";
    $(function () {
        //查找是否有优惠券
        Dolphin.ajax({
            url: CTX + '/api/770d4227ef734031b8e103aec1142d47@id=<%= userData.id%>',
            type: 'get',
            forceUrl: 'true',
            onSuccess: function (resData) {
                if(resData.rows.length > 0){
                    var couponArray = [];
                    $.each(resData.rows , function(idx,obj){
                        var item = {};
                        var itemType = 'CT01' == obj.couponType ? '现金券' : '折扣券';
                        var itemUnit = 'CT01' == obj.couponType ? '元' : '%';
                        item.title = obj.name+"("+itemType+" : "+obj.couponVal+" "+itemUnit+")";
                        item.value = obj.id;
                        couponArray.push(item);
                    });
                    couponArray.push({'title' : '', 'value' : ''});
                    couponArray.push({'title' : '', 'value' : ''});
                    $("#useCoupon").select({
                        title: "选择优惠券",
                        items: couponArray,
                        onChange: function(d) {
                            var couponValEnd = d.titles.lastIndexOf(' ',d.titles.length);
                            var couponValStart = d.titles.lastIndexOf(' ',couponValEnd-1);
                            var couponVal = d.titles.substring(couponValStart+1,couponValEnd);

                            var couponTypeStart = d.titles.indexOf('(');
                            var couponType = d.titles.substr(couponTypeStart+1,3);

                            var rentPrice = $('#rentPrice').val();
                            var realPay = 0;
                            if('现金券' == couponType){
                                realPay = Dolphin.accSub(rentPrice,couponVal);
                                $("#couponAmount").val(couponVal);
                            }else{
                                realPay = Dolphin.accMul(rentPrice,Dolphin.accDiv(couponVal,100));
                                $("#couponAmount").val(Dolphin.accSub(rentPrice,realPay));
                            }
                            $('.orderAmount').text('￥'+realPay+'(已使用优惠券)');
                            $('#coupon_id').val(d.values);

                        }
                    });

                }
            }
        });

        let datePickerFirstFlag = true;

        $("#dateTimePicker").datetimePicker({
            times: function () {
                return [
                    {
                        values: (function () {
                            var hours = [];
                            for (var i=0; i<24; i++) hours.push(i > 9 ? i : '0'+i);
                            return hours;
                        })()
                    },
                    {
                        divider: true,  // 这是一个分隔符
                        content: '时'
                    }
                ];
            },
            onChange: function (picker, values, displayValues) {
                console.log(values);
                var _beginTimePick=values[0]+"-"+values[1]+"-"+values[2]+" "+values[3]+":00:00";
                let timeGet=$('#timeSet').val().substring(4);
                let isTime;
                switch (timeGet){
                    case '0':
                        isTime=0;
                        break;
                    case '3':
                        isTime=3;
                        break;
                    case '5':
                        isTime=5;
                        break;
                    case '8':
                        isTime=8;
                        break;
                }
                let endHour=parseInt(values[3])+isTime;
                if(endHour<10){
                    endHour="0"+endHour;
                }
                let endDay=values[2];
                if(endHour>=24){
                    endHour=endHour-24;
                    endDay=parseInt(endDay)+1;
                }
                var _endTimePick=values[0]+"-"+values[1]+"-"+endDay+" "+endHour+":00:00";
                $('input[name="arrivedDate"]').val(_beginTimePick);
                $('input[name="leavedDate"]').val(_endTimePick);
            },
        });

        var dateRange1 = new pickerDateRange('datePicker', {
            stopToday : false,
            isTodayValid : true,
            startDateId : 'arrivedDate',
            endDateId : 'leavedDate',
//            startDate: '2015-11-05',
//            endDate: '2015-11-06',
//            dayRangeMax : false,
            needCompare : false,
            autoSubmit : false,
            inputTrigger : 'input_trigger1',
            theme : 'ta',
            success: function(obj) {
                var days = Dolphin.strDateDifference(obj.startDate,obj.endDate)
                $('#days').val(days);
                var price = $('#dayPrice').val();
                var amount = Dolphin.accMul(days,price);
                $('.orderAmount').text('￥'+amount);
                $('#rentPrice').val(amount);
                $('.useCoupon').show();
            }
        });
        $('#datePicker').focus(function () {
            $('[id^="calendar_"]').css({
                'left': 0,
                'top': 'auto',
                'bottom': 0,
            });
        })
        $('#datePicker').click(function () {
            $('[id^="calendar_"]').css({
                'left': 0,
                'top': 'auto',
                'bottom': 0,
            });
        })
//        $("#datePicker").calendar({
//            multiple: true,
//            value: [],
//            onDayClick: function (p, dayContainer, year, month, day) {
//                if(datePickerFirstFlag == true){
//                    datePickerFirstFlag = false;
//                    let removeDate = [].concat(p.value);
//                    removeDate.forEach(function (date) {
//                        p.addValue(date);
//                    });
//                }else if(datePickerFirstFlag == false){
//                    datePickerFirstFlag = true;
//                    let startDate = p.value[0];
//                    let endDate = new Date(year, month, day).getTime();
//                    if(startDate != endDate){
//                        let minDate, maxDate;
//                        let oneDayTime = 1000 * 60 * 60 * 24;
//                        if(endDate > startDate){
//                            minDate = startDate + oneDayTime;
//                            maxDate = endDate;
//                        }else{
//                            minDate = endDate + oneDayTime;
//                            maxDate = startDate;
//                        }
//                        for(;minDate < maxDate;minDate+=oneDayTime){
//                            p.addValue(minDate);
//                        }
//                    }
//                }
//            },
//            formatValue: function (p, values) {
//                let minDate = values[0];
//                let maxDate = values[values.length - 1];
//                if(minDate > maxDate){
//                    minDate = maxDate;
//                    maxDate = values[0];
//                }
//
//                minDate = Dolphin.date2string(new Date(minDate));
//                maxDate = Dolphin.date2string(new Date(maxDate));
//
//                if(values.length > 1){
//                    $('input[name="arrivedDate"]').val(minDate);
//                    $('input[name="leavedDate"]').val(maxDate);
//                    return `${minDate} 至 ${maxDate}`;
//                }else{
//                    return '';
//                }
//            }
//        });

        $('.timeHouse, .dayHouse, .bedNumber , .useCoupon').hide();
        //切换入住方式
        $('#orderType').change(function () {
            if($(this).val() == 'SRM01'){//钟点房
                var timeSetObj = JSON.parse('<%= data.shortPrices && JSON.stringify(data.shortPrices); %>'.replace(/&#34;/g, '"') || "{}");
                if(timeSetObj['SRT03'] == undefined ||
                    timeSetObj['SRT05'] == undefined ||
                    timeSetObj['SRT08'] == undefined ){
                    $.alert("该房间暂不支持钟点房");
                    $(this).val('');
                    $('.timeHouse').hide();
                    $('.dayHouse').hide();
                }else{
                    $('.timeHouse').show();
                    $('.dayHouse').hide();
                }

            }else if($(this).val() == 'SRM02'){//日租
                $('.timeHouse').hide();
                $('.dayHouse').show();
            }else{
                $('.timeHouse').hide();
                $('.dayHouse').hide();
            }

            $("#rentPrice").val('');
            $("#couponAmount").val('');
            $("#days").val('');
            $("#coupon_id").val('');
            $("#useCoupon").val('');
            $(".useCoupon").hide();
            $('.orderAmount').text('￥0');

        });

        //切换钟点房类型
        $("#timeSet").change(function(){
            var timeSetObj = JSON.parse('<%= data.shortPrices && JSON.stringify(data.shortPrices); %>'.replace(/&#34;/g, '"') || "{}");
            if($(this).val() == 'SRT03' && timeSetObj['SRT03'] != undefined){
                $('.orderAmount').text('￥'+timeSetObj['SRT03']);
                $('#rentPrice').val(timeSetObj['SRT03']);
                $('.useCoupon').show();
            }else if($(this).val() == 'SRT05' && timeSetObj['SRT03'] != undefined){
                $('.orderAmount').text('￥'+timeSetObj['SRT05']);
                $('#rentPrice').val(timeSetObj['SRT03']);
                $('.useCoupon').show();
            }else if($(this).val() == 'SRT08' && timeSetObj['SRT03'] != undefined){
                $('.orderAmount').text('￥'+timeSetObj['SRT08']);
                $('#rentPrice').val(timeSetObj['SRT03']);
                $('.useCoupon').show();
            }else{
                $("#rentPrice").val('');
                $("#couponAmount").val('');
                $("#days").val('');
                $("#coupon_id").val('');
                $("#useCoupon").val('');
                $(".useCoupon").hide();
                $('.orderAmount').text('￥0');
            }
        });

        //是否加床
        $('#bedFlag').change(function () {
            if(this.checked){
                $('.bedNumber').show();
            }else{
                $('.bedNumber').hide();
            }
        })

        //提交订单
        $("#submitBtn").click(function () {

            let data = Dolphin.form.getValue("#reservedForm");
            if(data.arrivedDate.length>10){
                data.arrivedDate = data.arrivedDate
            }else{
                data.arrivedDate = data.arrivedDate+" 00:00:00";
            }
            if(data.leavedDate.length>10){
                data.leavedDate = data.leavedDate
            }else{
                data.leavedDate = data.leavedDate+" 00:00:00";
            }
            data.contactName = '<%= userData.name %>';
            data.contactMobile = '<%= userData.phone %>';
            data.orderStatus = "OS00";
            data.rentPrice = Dolphin.accSub(data.rentPrice,$("#couponAmount").val());

            if(data.rentPrice <= 0){
                $.alert('订单金额可能存在问题，不允许提交订单！');
                return;
            }

            Dolphin.ajax({
                url:CTX+'/api/f266ff4abe8d42bcb86931f7acc827be',
                type:'put',
                forceUrl:'true',
                data: Dolphin.json2string(data),
                onSuccess:function (resData) {
                    let id = resData.value.id;
                    let currentopenid='<%= session.openId %>';

                    Dolphin.ajax({
                        url:CTX+'/api/123df51d6af845aeb13db4608eb89778',
                        forceUrl:'true',
                        type: Dolphin.requestMethod.POST,
                        data: Dolphin.json2string({ properties : { id : id }}),
                        onSuccess: function(reData){

                            var obj = reData.value.properties;
                            //客户下单给管理员发送消息确认订单
                            var msgData = {
                                "url" : "http://"+Dolphin.wechatUrl+"/yams/view/butlerIndex?openId="+obj.managerWeChat,
                                "openid" : obj.managerWeChat,
                                "first" : "管理员，您好！有客户下短租订单，请尽快确认",
                                "keyword1" : obj.apartmentName+"(房间号："+obj.houseNumber+")",
                                "keyword2" : obj.arrivedDate,
                                "keyword3" : obj.leavedDate,
                                "keyword4" : obj.rentPrice,
                                "keyword5" : '短租',
                                "remark" : "若有疑问请与管理员("+obj.managerName+","+obj.managerPhone+")联系"
                            }
                            Dolphin.ajax({
                                url: '<%= global.config.contextPath == '/' ? '' : global.config.contextPath %>/wexin'
                                +'/sendPayMsg',
                                type: Dolphin.requestMethod.POST,
                                data: Dolphin.json2string(msgData),
                                forceUrl: true,
                                onSuccess: function (reData) {
                                    //location.href = CTX+"/view/shortRentOrder?houseId="+houseId+"&openId="+openId;
                                    location.href = CTX+"/view/shortRentOrder?id="+id+"&openId="+currentopenid;
                                }
                            });
                        }
                    });

                }
            });
        });
    });
</script>
</body>
</html>